// directive 插件管理
import { DirectiveBinding } from "vue";
import { BgCache } from './utils';

// 图片缓存插件
const imageCache = {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
        const imgUrl = binding.value; // 图片路径（如 @/assets/button9.png）
        updateBackground(el, imgUrl);
    },
    updated(el: HTMLElement, binding: DirectiveBinding) {
        const imgUrl = binding.value;
        updateBackground(el, imgUrl);
    },
}

const imageMap = {
    bg4: import('@/assets/bg4.png'),
    button3: import('@/assets/button3.png'),
    button13: import('@/assets/button13.png'),
    button9: import('@/assets/button9.png'),
    button6: import('@/assets/button6.png'),
    roomBg1: import('@/assets/roomBg1.png'),
} as any

// 动态获取图片 URL
const getImageUrl = async (name: string) => {
    const module = await imageMap[name];
    return module.default; // 返回解析后的 URL（带哈希）
};

const updateBackground = async (el: HTMLElement, imgUrl: string) => {
    // 查看元素是否已经存在背景
    if (el.style.backgroundImage.indexOf('url') !== -1) return // 避免重复加载
    // Blob 转 Base64
    function blobToBase64(blob: Blob) {
        return new Promise((resolve) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result);
            reader.readAsDataURL(blob);
        });
    }

    try {
        // 1. 检查 IndexedDB 是否有 Base64 缓存
        imgUrl = await getImageUrl(imgUrl); // 输出 "/assets/bg4.png"
        imgUrl = new URL(imgUrl, import.meta.url).href; // 完整 URL
        const cachedBase64 = await BgCache.getCachedImage(imgUrl);
        if (cachedBase64) {
            el.style.backgroundImage = `url(${cachedBase64})`;
            console.log('indexDB存在以缓存的图片 直接加载', imgUrl);
            return;
        }

        // 2. 无缓存时，加载图片并转为 Base64
        const response = await fetch(imgUrl);
        const blob = await response.blob();
        // 检查blob类型
        if (blob.type !== 'image/png') {
            console.error('blob类型不是image/png', blob.type, imgUrl);
            return;
        }
        const base64 = await blobToBase64(blob) as string;

        // 3. 存储 Base64 并设置背景
        await BgCache.cacheImage(imgUrl, base64);
        el.style.backgroundImage = `url(${base64})`;
        console.log('indexDB首次缓存图片 图片路径', imgUrl);
    } catch (error) {
        console.error('背景图片加载失败:', error);
    }
}

export {
    imageCache,
}